#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QSerialPortInfo>
#include <QVBoxLayout>
#include <QDateTime>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , isCheckEnter(false)
    , isCheckLineBreak(false)
    , isTimeSpan(false)
    , isTimeSend(false)
    , isHexSend(false)
    , isHexView(false)
    , m_serial(new SerialPortForm(this))
    , m_tcpServer(new TcpServerForm(this))
    , m_tcpClient(new TcpClientForm(this))
    , m_udp(new UdpClientForm(this))
    , m_layout(nullptr)
    , m_timer(nullptr)
{
    ui->setupUi(this);

    ui->checkBox_timespan->setChecked(true);
    ui->checkBox_show_send->setChecked(true);
    this->isTimeSpan = true;

    connect(ui->checkBox_enter, &QCheckBox::clicked, this, [=](){
        if(ui->checkBox_enter->isChecked()){
            this->isCheckEnter = true;
        }else{
            this->isCheckEnter = false;
        }
    });

    connect(ui->checkBox_linebreak, &QCheckBox::clicked, this, [=](){
        if(ui->checkBox_linebreak->isChecked()){
            this->isCheckLineBreak = true;
        }else{
            this->isCheckLineBreak = false;
        }
    });

    connect(ui->checkBox_timespan, &QCheckBox::clicked, this, [=](){
        if(ui->checkBox_timespan->isChecked()){
            this->isTimeSpan = true;
        }else{
            this->isTimeSpan = false;
        }
    });

    connect(ui->checkBox_time_send, &QCheckBox::clicked, this, [=](){
        if(ui->checkBox_time_send->isChecked()){
            this->isTimeSend = true;
        }else{
            this->isTimeSend = false;
        }
    });

    connect(ui->checkBox_hex_send, &QCheckBox::clicked, this, [=](){
        if(ui->checkBox_hex_send->isChecked()){
            this->isHexSend = true;
        }else{
            this->isHexSend = false;
        }
    });

    connect(ui->checkBox_hex_view, &QCheckBox::clicked, this, [=](){
        if(ui->checkBox_hex_view->isChecked()){
            this->isHexView = true;
        }else{
            this->isHexView = false;
        }
    });

    connect(ui->comboBox, &QComboBox::currentTextChanged, this, &MainWindow::on_comboBox_currentTextChanged);
    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::slot_pushButton_clicked);
    connect(ui->checkBox_time_send, &QCheckBox::stateChanged, this, &MainWindow::slot_checkbox_timer_send);

    connect(this->m_serial, &SerialPortForm::SigData, this, &MainWindow::slot_textEdit_receive);
    connect(this->m_tcpClient, &TcpClientForm::SigData, this, &MainWindow::slot_textEdit_receive);
    connect(this->m_tcpServer, &TcpServerForm::SigData, this, &MainWindow::slot_textEdit_receive);
    connect(this->m_udp, &UdpClientForm::SigData, this, &MainWindow::slot_textEdit_receive);

    connect(this->m_tcpServer, &TcpServerForm::SigExtra, this, &MainWindow::slot_extra_information);


    ui->comboBox->clear();
    ui->comboBox->addItem("Serial");
    ui->comboBox->addItem("TCP Client");
    ui->comboBox->addItem("TCP Server");
    ui->comboBox->addItem("UDP");
    ui->comboBox->setCurrentIndex(0);
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::clearLayout()
{
    if(ui->widget->layout() != nullptr)
    {
        QLayoutItem* child = nullptr;
        while((child = ui->widget->layout()->takeAt(0)) != nullptr)
        {
            if(child->widget() != nullptr)
            {
                child->widget()->setParent(NULL);
                delete child;
            }
        }
    }else{
        QVBoxLayout* layout = new QVBoxLayout();
        ui->widget->setLayout(layout);
    }
}



void MainWindow::on_comboBox_currentTextChanged(const QString &arg1)
{
    this->clearLayout();

    if(arg1 == "TCP Client"){
        this->m_enActive = MainWindow::enActive::enAcTcpClient;
        ui->widget->layout()->addWidget(this->m_tcpClient);
    }else if(arg1 == "TCP Server"){
        this->m_enActive = MainWindow::enActive::enAcTcpServer;
        ui->widget->layout()->addWidget(this->m_tcpServer);
    }else if(arg1 == "UDP"){
        this->m_enActive = MainWindow::enActive::enAcUdp;
        ui->widget->layout()->addWidget(this->m_udp);
    }else{
        this->m_enActive = MainWindow::enActive::enAcSerial;
        ui->widget->layout()->addWidget(this->m_serial);
    }
}


void MainWindow::slot_pushButton_clicked()
{
    this->m_param.IsCheckEnter      = ui->checkBox_enter->isChecked();
    this->m_param.IsCheckLineBreak  = ui->checkBox_linebreak->isChecked();
    this->m_param.IsHexSend         = ui->checkBox_hex_send->isChecked();
    this->m_param.IsHexView         = ui->checkBox_hex_view->isChecked();
    this->m_param.IsTimeSend        = ui->checkBox_time_send->isChecked();
    this->m_param.IsTimeSpan        = ui->checkBox_timespan->isChecked();
    this->m_param.TimeInterval      = ui->lineEdit_timer->text().toInt();

    if(this->isHexSend){
        this->m_param.Array = QByteArray::fromHex(ui->plainTextEdit_input->toPlainText().toLatin1());
    }else{
        this->m_param.Array = ui->plainTextEdit_input->toPlainText().toLatin1();
    }

    if(this->isCheckEnter){
        this->m_param.Array.append('\r');
    }

    if(this->isCheckLineBreak){
        this->m_param.Array.append('\n');
    }

    switch(this->m_enActive){
    case MainWindow::enActive::enAcSerial:
        if(this->m_serial->IsOpen()){
            this->m_serial->Send(this->m_param);
        }
        break;
    case MainWindow::enActive::enAcTcpClient:
        this->m_tcpClient->Send(this->m_param);
        break;
    case MainWindow::enActive::enAcTcpServer:
        this->m_tcpServer->Send(this->m_param);
        break;
    case MainWindow::enActive::enAcUdp:
        this->m_udp->Send(this->m_param);
        break;
    default:break;
    }

    if(ui->checkBox_show_send->isChecked()){
        QString builder;
        if(this->isTimeSpan){
            builder.append("["+ QDateTime::currentDateTime().toString("yy-MM-dd HH:mm:ss.zzz") +"]" + " 发   ");
        }

        if(this->isHexView){
            builder.append(m_param.Array.toHex(' ').toUpper());
        }else{
            builder.append(m_param.Array);
        }

        ui->plainTextEdit_output->appendPlainText(builder);
    }
}


void MainWindow::slot_extra_information(const QString& extra)
{
    QString builder;
    if(this->isTimeSpan){
        builder.append("[" + QDateTime::currentDateTime().toString("yy-MM-dd HH:mm:ss.zzz") + "] 消息");
        builder.append("   ");
    }
    builder.append(extra);
    ui->plainTextEdit_output->appendPlainText(builder);
}



void MainWindow::slot_textEdit_receive(const QByteArray& data)
{
    QString builder;
    if(this->isTimeSpan){
        builder.append("[" + QDateTime::currentDateTime().toString("yy-MM-dd HH:mm:ss.zzz") + "] 收");
        builder.append("   ");
    }

    if(this->isHexView){
        builder.append(data.toHex(' ').toUpper());
    }else{
        builder.append(data);
    }

    ui->plainTextEdit_output->appendPlainText(builder);
}

#include <QMessageBox>
void MainWindow::slot_checkbox_timer_send(int value)
{
    bool bl = false;
    int interval = ui->lineEdit_timer->text().toInt(&bl);
    if(interval <= 0 || !bl){
        QMessageBox msgBox;
        msgBox.setText("定时发送时间设置错误,请设置有效整数(单位ms)");
        msgBox.setInformativeText("");
        msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::Yes);
        msgBox.exec();
        ui->checkBox_time_send->setChecked(false);
        return;
    }

    switch(this->m_enActive){
    case MainWindow::enActive::enAcSerial:
        if(!this->m_serial->IsOpen()){
            QMessageBox msgBox;
            msgBox.setText("设备没有打开.");
            msgBox.setInformativeText("还要发送么?");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Yes);
            int ret = msgBox.exec();
            if(ret != QMessageBox::Yes){
                return;
            }
        }
        break;
    case MainWindow::enActive::enAcTcpClient:
        if(!this->m_tcpClient->IsOpen()){
            QMessageBox msgBox;
            msgBox.setText("设备没有打开.");
            msgBox.setInformativeText("还要发送么?");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Yes);
            int ret = msgBox.exec();
            if(ret != QMessageBox::Yes){
                return;
            }
        }
        break;
    case MainWindow::enActive::enAcTcpServer:
        if(!this->m_tcpServer->IsOpen()){
            QMessageBox msgBox;
            msgBox.setText("设备没有打开.");
            msgBox.setInformativeText("还要发送么?");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Yes);
            int ret = msgBox.exec();
            if(ret != QMessageBox::Yes){
                return;
            }
        }
        break;
    case MainWindow::enActive::enAcUdp:
        if(!this->m_udp->IsOpen()){
            QMessageBox msgBox;
            msgBox.setText("设备没有打开.");
            msgBox.setInformativeText("还要发送么?");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
            msgBox.setDefaultButton(QMessageBox::Yes);
            int ret = msgBox.exec();
            if(ret != QMessageBox::Yes){
                return;
            }
        }
        break;
    default:break;
    }

    if(value == Qt::Unchecked){
        if(m_timer){
            m_timer->stop();
        }
    }else if(value == Qt::Checked){
        if(nullptr == m_timer){
            m_timer = new QTimer(this);
            connect(m_timer, &QTimer::timeout, this, [=](){
                this->slot_pushButton_clicked();
            });
        }
        m_timer->setInterval(ui->lineEdit_timer->text().toInt());
        m_timer->start();
    }
}

























